﻿package {
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;

	public class Server extends MovieClip {

		private var socket:Socket;
		public var socketName : String;
		public var connected:Boolean = false;

		public function Server(strName:String) {
			socketName = strName;
		}
		//连接事件
		public function socketConnect(_ip:String,_port:int):void {
			if (connected)
			{
				socket.close();
			}
			socket = new Socket;
			socket.connect(_ip,_port);
			socket.addEventListener(IOErrorEvent.IO_ERROR,errorFun);
			socket.addEventListener(Event.CONNECT,connectFun);
		}
		//发送事件
		public function socketSend(str:String):void {
			socket.writeMultiByte(str,"gbk");
			socket.flush();
		}
		//失败事件
		private function errorFun(event:IOErrorEvent):void {
			close();
			dispatchEvent(new ApplySocketEvent(ApplySocketEvent.ERROR));
		}
		//断开事件
		public function close():void {
			clearEvent();
			connected=false;
			socket.close();
			socket=null;
		}
		//连接成功处理函数
		private function connectFun(event:Event):void {
			//向服务器发送登陆成功信息
			socket.writeMultiByte(socketName,"gbk");
			socket.flush();
			connected = true;//给连接标记赋值
			clearEvent();//清除某些侦听事件
			//侦听来自服务器的信息
			socket.addEventListener(ProgressEvent.SOCKET_DATA,socketDataFun);
			socket.addEventListener(Event.CLOSE,closeFun);
			//抛出连接成功事件
			dispatchEvent(new ApplySocketEvent(ApplySocketEvent.CONNECT));
		}
		//侦听来自服务器的信息
		private function socketDataFun(event:ProgressEvent):void {
			while (socket.bytesAvailable) {
				var strData:String = socket.readMultiByte(socket.bytesAvailable,"gb2312");
				var Events:ApplySocketEvent = new ApplySocketEvent(ApplySocketEvent.SYNC);
				Events.data = strData + "\n";
				dispatchEvent(Events);//抛出已接收事件
				strData = null;
				Events = null;
			}
		}
		//关闭事件
		private function closeFun(event:Event):void {
			connected=false;
			dispatchEvent(new ApplySocketEvent(ApplySocketEvent.CLOSE));
		}
		//清理事件侦听
		private function clearEvent():void {
			if (socket != null)
			{
				if (socket.hasEventListener(IOErrorEvent.IO_ERROR))
				{
					socket.removeEventListener(IOErrorEvent.IO_ERROR,errorFun);
				}
				if (socket.hasEventListener(Event.CONNECT))
				{
					socket.removeEventListener(Event.CONNECT,connectFun);
				}
				if (socket.hasEventListener(ProgressEvent.SOCKET_DATA))
				{
					socket.removeEventListener(ProgressEvent.SOCKET_DATA,socketDataFun);
				}
				if (socket.hasEventListener(Event.CLOSE))
				{
					socket.removeEventListener(Event.CLOSE,closeFun);
				}
			}
		}
	}
}